#include "Q6_3.h"

void Invert(char *input)
{
	int length = strlen(input);
	int mid_idx = length/2;
	for(int i =0; i<mid_idx; i++)
	{
		char temp = input[i];
		input[i] = input[length-i-1];
		input[length-i-1] = temp;
	}
}

//ghi chu: kho hieu ve nha tinh tiep
void copyString_with_memcpy(char *input, int offset, int length, bool invert, char *output, int offset_output)
{
	int size1 = strlen(input);
	int size2 = strlen(output);

	//calculate size of copy source from input
	length = (size1 - offset) > length ? length : (size1 - offset);

	char *str = new char[length+1];
	str[length] = '\0';

	memcpy(str, input+offset, length);

	if(invert)
		Invert(str);

	//calculate size of copy source from temp
	length = (size2-offset_output) > length ? length : (size2-offset_output);
	memcpy(output+offset_output, str, length);
}

void copyString_with_strcpy(char *input, int offset, int length, bool invert, char *output, int offset_output)
{
	int size1 = strlen(input);
	int size2 = strlen(output);

	length = (size1 - offset) > length ? length : (size1 - offset);

	int i = 0;
	char *str_src = new char[length];
	while(input[offset+i] != '\0' && i<length)
	{
		str_src[i] = input[offset+i];
		i++;
	}
	str_src[length] = '\0';

	if(invert)
		Invert(str_src);

	const char *str = str_src; 
	strcpy(output + offset_output, str);
	output[size2] = '\0';
}

void copyString_without_memcpy_strcpy(char *input, int offset, int length, bool invert, char *output, int offset_output)
{
	int size1 = strlen(input);
	int size2 = strlen(output);

	length = (size1 - offset) > length ? length : (size1 - offset);

	int i = 0;
	char *str_src = new char[length];
	while(input[offset+i] != '\0' && i<length)
	{
		str_src[i] = input[offset+i];
		i++;
	}
	str_src[length] = '\0';

	if(invert)
		Invert(str_src);

	length = (size2-offset_output) > length ? length : (size2-offset_output);
	i=0;
	while(output[offset_output+i] != '\0' && i<length)
	{
		output[offset_output+i] = str_src[i];
		i++;
	}
}

void q6_3_run()
{
	printf("Q6.3\n");
	char *st1 = "Hello World";
	char *st2 = new char[15];
	//st2 = "My name is C++";
	st2[0] = 'M';
	st2[1] = 'y';
	st2[2] = ' ';
	st2[3] = 'n';
	st2[4] = 'a';
	st2[5] = 'm';
	st2[6] = 'e';
	st2[7] = ' ';
	st2[8] = 'i';
	st2[9] = 's';
	st2[10] = ' ';
	st2[11] = 'C';
	st2[12] = '+';
	st2[13] = '+';
	st2[14] = '\0';

	printf("%s\n", st1);
	printf("%s\n", st2);
	copyString_with_memcpy(st1, 6, 5, true, st2, 11);
	printf("%s\n", st2);
	copyString_with_strcpy(st1, 6, 5, true, st2, 11);
	printf("%s\n", st2);
	copyString_without_memcpy_strcpy(st1, 6, 5, true, st2, 11);
	printf("%s\n", st2);
}